<?php
/**
 * File: Project.class.php
 * Author: camy <375766145@qq.com>
 * Time: 2018/3/19 15:05
 */

namespace Common\Service;

use Think\Page;

class Project extends Base
{
    /**
     * 项目参数验证
     * @param $data
     * @return bool
     */
    protected function validateProject($data)
    {
        $model = M('project');
        $rule = [
            ['name', 'require', '项目名称不能为空', 1],
            ['amount', '/^[0-9]+(.[0-9]+)?$/', '项目金额必须为数字', 1],
            ['content', 'require', '项目内容不能为空', 1],
            ['begin_time', 'require', '计划开工日期不能为空', 1],
            ['end_time', 'require', '计划竣工日期不能为空', 1],
        ];
        return $this->validate($model, $rule, $data);
    }

    /**
     * 新建项目
     * @param $data
     * @param $managerId
     * @return bool
     */
    public function createProject($data, $managerId)
    {
        //判断项目管理员
        $userService = User::instance();
        $manager = $userService->getUserById($managerId);
        if (!$manager) {
            $this->error = '项目管理员不存在';
            return false;
        }
        //验证参数
        $res = $this->validateProject($data);
        if (!$res) {
            return false;
        }
        try {
            M()->startTrans();
            //保存项目
            $projectId = M('project')->add($data);
            if (!$projectId) {
                throw new \Exception();
            }
            //保存负责人
            $memberData['project_id'] = $projectId;
            $memberData['user_id'] = $managerId;
            $memberData['user_type'] = 2;
            $memberData['superior_id'] = 0;
            $memberId = M('projectMember')->add($memberData);
            if (!$memberId) {
                throw new \Exception();
            }
            M()->commit();
            return $projectId;
        } catch (\Exception $e) {
            M()->rollback();
            return false;
        }
    }

    /**
     * 更新项目
     * @param $data
     * @return bool
     */
    public function updateProject($data)
    {
        //验证参数
        $res = $this->validateProject($data);
        if (!$res) {
            return false;
        }
        return M('project')->save($data);

    }

    /**
     * 获取项目列表
     * @param $search
     * @param $status
     * @return array
     */
    public function getProjectList($search, $status)
    {
        $param['status'] = $status;
        if (!empty($search)) {
            $map['name'] = ['like', "%{$search}%"];
            $param['search'] = $search;
        }
        $map['status'] = $status;
        $map['deleted_at'] = 0;
        $count = M('project')->where($map)->count();
        $page = new Page($count, $this->pageSize, $param);
        $list = M('project')
            ->where($map)
            ->field('id,name,amount,created_at')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order('created_at desc')
            ->select();
        return ['list' => $list, 'show' => $page->show()];

    }

    /**
     *  获取项目详情
     * @param $id
     * @return mixed
     */
    public function getProjectDetail($id)
    {
        $project = M('project')
            ->where(['id'=>$id,'deleted_at' => 0])
            ->find();
        if (!$project) {
            $this->error = '项目不存在或已删除';
            return false;
        }
        unset($project['deleted_at']);
        //详细地址
        $address = Address::instance();
        $province = $address->name($project['province']);
        $city = $address->name($project['city']);
        $area = $address->name($project['area']);
        $project['detail_address'] = $province . $city . $area . $project['address'];
        //项目负责人
        $manager = M('projectMember')
            ->alias('pm')
            ->join('left join user u on u.id=pm.user_id')
            ->where(['pm.project_id' => $id, 'pm.user_type' => 2])
            ->field('u.name,u.id')
            ->find();
        $project['manager'] = $manager['name'];
        //项目进度
        $project['schedules'] = M('projectSchedule')
            ->field('schedule,updated_at')
            ->where(['project_id' => $id])
            ->select();
        return $project;
    }

    protected function validateProjectMember($data)
    {
        $model = M('projectMember');
        $rule = [
            ['project_id', '/[1-9]+/', '项目不能为空', 1],
            ['user_id', '/[1-9]+/', '成员不能为空', 1],
        ];
        return $this->validate($model, $rule, $data);
    }

    /**
     * 添加项目成员
     * @param $projectId
     * @param $userId
     * @param $userRemark
     * @return bool|mixed
     */
    public function addProjectMember($projectId, $userId, $userRemark)
    {
        $data['project_id'] = $projectId;
        $data['user_id'] = $userId;
        $data['user_remark'] = $userRemark;
        //验证参数
        $res = $this->validateProjectMember($data);
        if (!$res) {
            return false;
        }
        //判断用户是否已经添加
        $userMember = M('projectMember')
            ->where(['user_id' => $userId, 'project_id' => $projectId])
            ->find();
        if ($userMember) {
            $this->error = '该用户已经添加';
            return false;
        }
        //登录用户身份
        $loginUserId = user()->id;
        $loginMember = M('projectMember')
            ->where(['user_id' => $loginUserId, 'project_id' => $projectId])
            ->find();
        if ($loginMember['user_type'] == 2) {
            //项目负责人
            $data['user_type'] = 1;
        } else {
            //专业负责人
            $data['user_type'] = 0;
        }
        $data['superior_id'] = $loginUserId;
        return M('projectMember')->add($data);


    }

    /**
     * 删除项目成员
     * @param $id
     * @return bool
     */
    public function deleteProjectMember($id)
    {
        $member = M('projectMember')->find($id);
        //登录用户身份
        $loginUserId = user()->id;
        //只能删除下级
        if ($member['superior_id'] != $loginUserId) {
            $this->error = '只能删除您的下级成员';
            return false;
        }
        //被删除者有下级则无法删除
        $childMember = M('projectMember')
            ->where(['superior_id' => $member['user_id']])
            ->select();
        if ($childMember) {
            $this->error = '该成员已有下级成员，无法删除';
            return false;
        }
        return M('projectMember')->where(['id' => $id])->delete();

    }

    /**
     * 获取项目成员
     * @param $projectId
     * @param  $userType
     * @return mixed
     */
    public function getProjectMember($projectId, $userType)
    {
        $model = M('projectMember')
            ->alias('pm')
            ->join('left join user u on pm.user_id=u.id')
            ->field('pm.id,pm.user_type type,pm.user_remark remark,u.name,u.avatar,u.department,u.position')
            ->where(['pm.project_id' => $projectId]);
        if ($userType !== null) {
            $model->where(['user_type' => intval($userType)]);
        }
        return $model->select();
    }
}